package com.tea.servlet;

import com.tea.entity.Order;
import com.tea.entity.OrderItem;
import com.tea.entity.Product;
import com.tea.entity.User;
import com.tea.service.OrderService;
import com.tea.service.ProductService;
import com.tea.service.impl.OrderServiceImpl;
import com.tea.service.impl.ProductServiceImpl;
import com.tea.util.URLUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 直接下单Servlet - 处理商品详情页的直接购买功能
 */
@WebServlet("/inorder")
public class InorderServlet extends HttpServlet {
    
    private final OrderService orderService = new OrderServiceImpl();
    private final ProductService productService = new ProductServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String action = req.getParameter("action");
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");
        
        try {
            // 验证用户登录状态
            if (user == null) {
                String redirectUrl = URLUtil.buildRedirectUrl("/login.jsp", "msg", "请先登录后再购买");
                resp.sendRedirect(redirectUrl);
                return;
            }
            
            if ("directBuy".equals(action)) {
                handleDirectBuy(req, resp, user);
            } else {
                String redirectUrl = URLUtil.buildRedirectUrl("/error.jsp", "msg", "无效的操作类型");
                resp.sendRedirect(redirectUrl);
            }
        } catch (Exception e) {
            e.printStackTrace();
            session.setAttribute("errorMsg", "直接购买失败: " + e.getMessage());
            resp.sendRedirect("/error.jsp");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 直接购买功能使用GET方法，如果有POST请求则重定向到GET
        doGet(req, resp);
    }
    
    /**
     * 处理直接购买逻辑
     */
    private void handleDirectBuy(HttpServletRequest req, HttpServletResponse resp, User user) throws Exception {
        // 获取参数
        String productIdStr = req.getParameter("productId");
        String quantityStr = req.getParameter("quantity");
        
        // 参数验证
        if (productIdStr == null || productIdStr.trim().isEmpty()) {
            String redirectUrl = URLUtil.buildRedirectUrl("/error.jsp", "msg", "商品ID不能为空");
            resp.sendRedirect(redirectUrl);
            return;
        }
        
        if (quantityStr == null || quantityStr.trim().isEmpty()) {
            String redirectUrl = URLUtil.buildRedirectUrl("/error.jsp", "msg", "购买数量不能为空");
            resp.sendRedirect(redirectUrl);
            return;
        }
        
        long productId;
        int quantity;
        
        try {
            productId = Long.parseLong(productIdStr);
            quantity = Integer.parseInt(quantityStr);
        } catch (NumberFormatException e) {
            String redirectUrl = URLUtil.buildRedirectUrl("/error.jsp", "msg", "参数格式错误");
            resp.sendRedirect(redirectUrl);
            return;
        }
        
        // 验证购买数量
        if (quantity <= 0) {
            String redirectUrl = URLUtil.buildRedirectUrl("/product-detail?productId=" + productId, "error", "购买数量必须大于0");
            resp.sendRedirect(redirectUrl);
            return;
        }
        
        // 获取商品信息
        Product product = productService.getProductById(productId);
        if (product == null) {
            String redirectUrl = URLUtil.buildRedirectUrl("/error.jsp", "msg", "商品不存在");
            resp.sendRedirect(redirectUrl);
            return;
        }
        
        // 验证库存
        if (quantity > product.getStock()) {
            String redirectUrl = URLUtil.buildRedirectUrl("/product-detail?productId=" + productId, "error", 
                "库存不足，当前库存：" + product.getStock());
            resp.sendRedirect(redirectUrl);
            return;
        }
        
        // 计算订单总金额
        double totalAmount = product.getPrice() * quantity;
        
        // 创建订单对象
        Order order = new Order();
        order.setUserId(user.getId());
        order.setStatus(0); // 待付款状态
        order.setTotalAmount(totalAmount);
        
        // 创建订单项列表
        List<OrderItem> orderItems = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setProductId(productId);
        orderItem.setQuantity(quantity);
        orderItem.setPrice(totalAmount); // 这里的price字段实际存储的是总价（单价 × 数量）
        orderItems.add(orderItem);
        
        // 调用Service层创建订单
        String orderId = orderService.createOrder(order, orderItems);
        
        // 重定向到订单详情页
        resp.sendRedirect("/order?action=view&orderId=" + orderId);
    }
}
